#!/usr/bin/python
import hal, time, serial
 
h = hal.component("serial-relays")
h.newpin("relay1", hal.HAL_BIT, hal.HAL_IN)
h.newpin("relay2", hal.HAL_BIT, hal.HAL_IN)
h.newpin("relay3", hal.HAL_BIT, hal.HAL_IN)
h.newpin("relay4", hal.HAL_BIT, hal.HAL_IN)
h.ready()
 
ser = serial.Serial('/dev/ttyUSB0', 115200, bytesize=8, parity='N', stopbits=1, timeout=0, xonxoff=0, rtscts=0)
 
rA = 0
rB = 0
rC = 0
rD = 0
 
def serial_command(r, cmd):
    while ser.inWaiting():
        pass
    ser.write(r)
    if True == cmd:
        ser.write('1')
    else:
        ser.write('0')
    ser.write ('\n')
 
 
try:
    while 1:
        if (rA != h.relay1):
            rA = h.relay1
            serial_command('1', rA)
        if (rB != h.relay2):
            rB = h.relay2
            serial_command('2', rB)
        if (rC != h.relay3):
            rC = h.relay3
            serial_command('3', rC)
        if (rD != h.relay4):
            rD = h.relay4
            serial_command('4', rD)
 
 
except KeyboardInterrupt:
    raise SystemExit
